import React, { useEffect, useState } from 'react'
import { Button, Drawer, Empty, Form, message, Space } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import { getUserList, addUser, editUser, updateUserStatus, resetPassword } from '@/api/user'
import { getOrgListSearch } from '@/api/org'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import './index.less'
import { ITableData } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import { useFormEdit } from './useFormAdd'
import CustomTable from '@/components/CustomTable'
import { orgTypeEnum, QSFORGID, STATUSBANDOPTIONS, STATUSNUM } from '@/constant'
import { useNavigate } from 'react-router-dom'
import { IOrgTableData } from '../Role/types'
import { useAppSelector } from '@/store/hooks'
import { PlusOutlined } from '@ant-design/icons'
import { onValuesChange } from '@/utils/onValuesChange'
import PermissionButton from '@/components/PermissionButton'
import useCachePage from '@/hooks/useCachePage'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormEdit] = useForm()
  const [isModalShow, setIsModalShow] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [orgOptions, setOrgOptions] = useState<IOptionItem[]>([])
  const orgId = useAppSelector((state) => state.user.user_info.orgId)
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getUserList, {
    form: form,
    defaultFieldsParams: {
      orgId: orgId + '',
      status: 1,
    },
    immediatelySend: false,
  })
  let timeoutOrg: ITimeoutType
  const qsfOrgId = Form.useWatch('org', FormEdit)?.value
  useEffect(() => {
    handleSearchOrg()
    handleCacheData()
  }, [])
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        orgId: orgId + '',
        status: 1,
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      form.setFieldsValue({
        ...cacheData,
      })
      setOrgOptions(cacheData?.orgOptions || [])
      delete cacheData?.orgOptions
      search({
        ...cacheData,
        orgId: cacheData?.orgId != null ? cacheData.orgId : null,
      })
    }
  }
  const onConfirm = async (values: any) => {
    setispedding(true)
    const paramsData: Record<string, any> = {
      orgId: values?.org?.value,
      orgName: values?.org?.label,
      name: values?.name,
      phone: values?.phone,
    }
    if (qsfOrgId == QSFORGID) {
      paramsData.workId = values?.workId
      paramsData.orgType = orgTypeEnum.SEVENFUN
    } else {
      paramsData.workId = ''
      paramsData.orgType = orgTypeEnum.SUPPLIER
    }
    let res
    if (!isEdit) {
      res = await addUser({ ...paramsData }).finally(() => setispedding(false))
    } else {
      const id = FormEdit.getFieldValue('id')
      res = await editUser({ id, ...paramsData }).finally(() => setispedding(false))
    }
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search(params)
      // search({ orgId: form.getFieldValue('orgId') })
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }
  const onEdit = (info: ITableData) => {
    FormEdit.setFieldsValue({ ...info, org: { value: info.orgId, label: info.orgName } })
    setIsEdit(true)
    setIsModalShow(true)
  }
  const resetPwd = async (id: number) => {
    const res = await resetPassword({ id })
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
      // search({ orgId: form.getFieldValue('orgId') })
    }
  }
  const handleSearchOrg = (newValue = '') => {
    if (timeoutOrg) {
      clearTimeout(timeoutOrg)
      timeoutOrg = null
    }
    const getOptions = async () => {
      const res = await getOrgListSearch<IOrgTableData>({
        orgNameKeyWord: newValue,
      })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: item.name,
              value: item.id,
            }
          }) || []
        setOrgOptions(data)
      }
    }
    timeoutOrg = setTimeout(getOptions, 500)
  }
  const onStatus = async (info: ITableData) => {
    const res = await updateUserStatus({
      status: info.status == STATUSNUM.CLOSE ? STATUSNUM.OPEN : STATUSNUM.CLOSE,
      id: info.id,
    })
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
      // search({ orgId: form.getFieldValue('orgId') })
    }
  }
  return (
    <PageContainer className="usermgr_page">
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['workId', 'name'], form)}
        searchConfig={[
          {
            label: '组织名称',
            name: 'orgId',
            type: 'Select',
            option: orgOptions,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchOrg,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
              onClear: () => {
                handleSearchOrg()
              },
            },
          },
          { label: '用户工号', name: 'workId', type: 'Input' },
          { label: '用户姓名', name: 'name', type: 'Input' },
          { label: '用户状态', name: 'status', type: 'Select', option: STATUSBANDOPTIONS },
        ]}
        onFinish={(vals: any) => {
          const paramsData = {
            ...vals,
            orgId: vals.orgId != undefined ? vals.orgId : null,
            status: vals.status != undefined ? vals.status : null,
          }
          search(paramsData)
          setCachePage({
            ...paramsData,
            orgOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          const paramsData = {
            current: 1,
            size: 10,
            status: 1,
            orgId: orgId + '',
          }
          setCachePage({
            ...paramsData,
          })
          reset()
          // handleSearchOrg()
        }}
        extra={
          <div className="table_extra_flex">
            <PermissionButton
              permission="addUser"
              type="primary"
              onClick={() => {
                setIsModalShow(true)
                setIsEdit(false)
              }}
              icon={<PlusOutlined />}
            >
              新建用户
            </PermissionButton>
          </div>
        }
      ></SearchForm>
      <CustomTable bordered columns={useIndexColumns(onEdit, resetPwd, params, onStatus, navigate)} {...tableProps} />
      <Drawer
        title={isEdit ? '编辑用户' : '新建用户'}
        maskClosable
        open={isModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button
                type="primary"
                onClick={() => FormEdit.validateFields().then((values) => onConfirm(values))}
                loading={ispedding}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={useFormEdit({ orgOptions, handleSearchOrg, qsfOrgId, reset })}
          form={FormEdit}
          onValuesChange={(changedValues) => onValuesChange(changedValues, ['name', 'workId', 'phone'], FormEdit)}
        />
      </Drawer>
    </PageContainer>
  )
}

export default Index
